package com.mlm.mlmapp.activity;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.androidannotations.annotations.AfterViews;
import org.androidannotations.annotations.Click;
import org.androidannotations.annotations.EActivity;
import org.androidannotations.annotations.Extra;
import org.androidannotations.annotations.ViewById;
import org.androidannotations.annotations.res.ColorRes;
import org.androidannotations.annotations.res.DrawableRes;
import org.androidannotations.annotations.sharedpreferences.Pref;
import org.json.JSONArray;
import org.json.JSONException;

import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.style.AbsoluteSizeSpan;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import com.androidquery.AQuery;
import com.androidquery.callback.AjaxCallback;
import com.androidquery.callback.AjaxStatus;
import com.flyco.tablayout.listener.OnTabSelectListener;
import com.flyco.tablayout.view.SimpleCardFragment;
import com.flyco.tablayout.view.SlidingTabLayout;
import com.mlm.mlmapp.R;
import com.mlm.mlmapp.adapter.view.AQProgressDialog;
import com.mlm.mlmapp.adapter.view.listener.DatepickerItemSelectedListener;
import com.mlm.mlmapp.cons.HTTPCons;
import com.mlm.mlmapp.interfaces.Prefs_;
import com.mlm.mlmapp.utils.CommonUtils;

/**
 * Activity which displays a login screen to the user, offering registration as
 * well.
 */
@EActivity(R.layout.date_picker)
public class DatePickerActivity extends BaseActivity implements HTTPCons,
		OnTabSelectListener {
	AQuery aq;
	@Pref
	Prefs_ pref;
	@Extra
	String id;
	@Extra
	String dateid;
	List<String> dates;
	HashMap<String, List<Times>> datetimes;
	int index;
	Map<String, Boolean> statusList;
	@ColorRes
	int red;
	@ColorRes
	int blacktext;
	@ColorRes
	int greyborder;
	private ArrayList<Fragment> mFragments = new ArrayList<>();
	private final String[] mTitles = {};
	private int daysInYear = 0;
	private String[] weekDays = { "星期日", "星期一", "星期二", "星期三", "星期四", "星期五",
			"星期六" };
	@ViewById
	ViewPager vp;
	@ViewById
	SlidingTabLayout tl;
	@ViewById
	Button apply;
	@DrawableRes
	Drawable red_edge_btn_long;
	@ViewById
	TextView tv_date;
@Extra
String couponid;
	@AfterViews
	void init() {
		String title=getTitle().toString();
		if(!"".equals(title)){
			((TextView) this.findViewById(R.id.tv_title)).setText(title);
		}
		
		aq = new AQuery(this);
		datetimes = new HashMap<String, List<Times>>();
		statusList = new HashMap<String, Boolean>();
		dates = new ArrayList<String>();
		vp.setAdapter(new MyPagerAdapter(getSupportFragmentManager()));
		vp.setOffscreenPageLimit(7);
		vp.setKeepScreenOn(true);
		getDates();
	}

	private void getDates() {
		HashMap<String, String> map = new HashMap<>();
		map.put("stylistinfoId", id);
		aq.progress(new AQProgressDialog(this)).ajax(CommonUtils.getURLStringParams(get_dates, map),
				JSONArray.class, new AjaxCallback<JSONArray>() {

					@Override
					public void callback(String url, JSONArray array,
										 AjaxStatus status) {
						// TODO Auto-generated method stub
						if (status.getCode() == -101) {
							Toast.makeText(aq.getContext(), "网络异常,请检查网络",
									Toast.LENGTH_SHORT);
							return;
						}
						if (status.getCode() != 200) {
							Toast.makeText(aq.getContext(),
									"网络异常:" + status.getCode(),
									Toast.LENGTH_LONG).show();
						} else {
							try {
								onDatesSuccess(array);
							} catch (JSONException e) {
								// TODO Auto-generated catch block
								e.printStackTrace();
							}
						}
					}

				});
	}

	private void getTimes(final String date) {
		HashMap<String, String> map = new HashMap<>();
		map.put("stylistinfoId", id);
		int start = date.indexOf("\n") + 1;
		map.put("currentDate", date.substring(start, date.length()));
		if(couponid!=null)
			map.put("userCouponId", couponid);
		aq.ajax(CommonUtils.getURLStringParams(get_times, map),
				JSONArray.class, new AjaxCallback<JSONArray>() {

					@Override
					public void callback(String url, JSONArray array,
										 AjaxStatus status) {
						// TODO Auto-generated method stub
						if (status.getCode() == -101) {
							Toast.makeText(aq.getContext(), "网络异常,请检查网络",
									Toast.LENGTH_SHORT);
							return;
						}
						if (status.getCode() != 200) {
							Toast.makeText(aq.getContext(),
									"网络异常:" + status.getCode(),
									Toast.LENGTH_LONG).show();
						} else {
							try {
								onTimesSuccess(date, array);
							} catch (JSONException e) {
								// TODO Auto-generated catch block
								e.printStackTrace();
							}
						}
					}

				});
	}

	@Override
	public void onTabSelect(int position) {
	}

	@Override
	public void onTabReselect(int position) {
	}

	private void onDatesSuccess(JSONArray array) throws JSONException {
		// TODO Auto-generated method stub
		String temp = "";
		for (int i = 0; i < array.length(); i++) {

			String date = getJsonString(array.getJSONObject(i), "appointDate");
			Calendar c = Calendar.getInstance();
			int currYear = c.get(Calendar.YEAR);
			int currMon = c.get(Calendar.MONTH);
			int currDate = c.get(Calendar.DAY_OF_YEAR);
			String arr[] = date.split("-");
			int paYear = Integer.valueOf(arr[0]);
			int paMon = Integer.valueOf(arr[1]) - 1;
			int paDay = Integer.valueOf(arr[2]);
			c.set(paYear, paMon, paDay);
			int newWeekday = c.get(Calendar.DAY_OF_WEEK_IN_MONTH);

			int paDate = c.get(Calendar.DAY_OF_YEAR);

			if (currYear == paYear) {
				if (currDate == paDate) {
					temp = "今天";
				} else if ((paDate - currDate) == 1) {
					temp = "明天";
				} else {
					int w = c.get(Calendar.DAY_OF_WEEK) - 1;
					if (w < 0)
						w = 0;
					temp = weekDays[w];
				}
			} else if ((paYear - currYear) == 1) {

				if ((currYear % 4 == 0 && currYear % 100 != 0)
						|| currYear % 400 == 0)
					daysInYear = 366;
				else
					daysInYear = 365;

				if (paDate + daysInYear - currDate == 1) {
					temp = "今天";
				} else if (paDate + daysInYear - currDate == 2) {
					temp = "明天";
				} else {
					int w = c.get(Calendar.DAY_OF_WEEK) - 1;
					if (w < 0)
						w = 0;
					temp = weekDays[w];
				}

			} else {
				int w = c.get(Calendar.DAY_OF_WEEK) - 1;
				if (w < 0)
					w = 0;
				temp = weekDays[w];
			}
			date = temp + "\n" + date;
			// if (i == array.length() - 1)
			// getTimes(date);
			// else
			// getTimes(date);
			//
			dates.add(date);
			// statusList.put(date, false);
		}
		tl.setViewPager(vp, dates.toArray(mTitles));
		for (String d : dates) {
			getTimes(d);
			statusList.put(d, false);
		}
	}

	private void onTimesSuccess(String key, JSONArray array)
			throws JSONException {
		// TODO Auto-generated method stub
		statusList.put(key, true);
		int start = key.indexOf("\n") + 1;
		String currDate = key.substring(start, key.length());
		List<Times> times = new ArrayList<Times>();
		for (int i = 0; i < array.length(); i++) {
			String status;
			int flag = getJsonInt(array.getJSONObject(i), "status");
			if (flag == 0) {
				status = "已预约";
			} else {
				status = "可预约";
			}
			String tempTimes = getJsonString(array.getJSONObject(i),
					"appointTimes");
			String res = tempTimes + "\n" + status;
			SpannableString span = new SpannableString(res);
			AbsoluteSizeSpan spansize = new AbsoluteSizeSpan(CommonUtils.sp2px(
					this, 12));
			span.setSpan(span, 0, tempTimes.length() - 1,
					Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
			Times t = new Times();
			t.setId(getJsonString(array.getJSONObject(i), "id"));
			t.setDate(currDate);
			t.setTime(tempTimes);
			t.setStatus(flag);
			times.add(t);
		}

		datetimes.put(key, times);
		// List<String> times=new ArrayList<String>();
		// for(int i=0;i<array.length();i++){
		// times.add(getJsonString(array.getJSONObject(i), "appointTimes"));
		// }
		// mFragments.add(SimpleCardFragment.getInstance(times));
		if (!statusList.containsValue(false)) {
			completeinit();
		}

	}

	private void completeinit() {
		int i = 0;
		for (String key : dates) {

			mFragments.add(SimpleCardFragment.getInstance(i, dateid,
					datetimes.get(key), new DatepickerItemSelectedListener() {

						@Override
						public void onItemClick(String id, String date,
								int index, TextView v) {
							// TODO Auto-generated method stub
							
							if (v != null) {
								v.setBackground(DatePickerActivity.this
										.getResources()
										.getDrawable(
												R.drawable.datepicker_list_item_checked));
								v.setTextColor(DatePickerActivity.this
										.getResources().getColor(R.color.white));

							}
							dateid = id;
							vp.setCurrentItem(index);
							if (!"".equals(dateid)) {
								apply.setBackground(red_edge_btn_long);
								apply.setTextColor(red);

								tv_date.setText(date);
								// vp.setCurrentItem(index);
							}
						}
					}));
			i++;
		}
		vp.getAdapter().notifyDataSetChanged();
	}

	@Click
	void apply() {
		Intent intent = new Intent();
		intent.putExtra("dateid", dateid);
		intent.putExtra("date", tv_date.getText());
		this.setResult(RESULT_OK, intent);
		this.finish();
	}

	@Override
	public void onBackPressed() {
		// TODO Auto-generated method stub
		Intent intent = new Intent();
		this.setResult(RESULT_CANCELED, intent);
		this.finish();
	}

	@Click
	void btn_back() {
		onBackPressed();
	}

	private class MyPagerAdapter extends FragmentPagerAdapter {
		public MyPagerAdapter(FragmentManager fm) {
			super(fm);
		}

		@Override
		public int getCount() {
			return mFragments.size();
		}

		@Override
		public CharSequence getPageTitle(int position) {
			return "";
		}

		@Override
		public Fragment getItem(int position) {
			return mFragments.get(position);
		}
	}

	public class Times {
		private String date;
		private String time;
		private String id;

		public String getDate() {
			return date;
		}

		public void setDate(String date) {
			this.date = date;
		}

		public String getTime() {
			return time;
		}

		public void setTime(String time) {
			this.time = time;
		}

		private int status;

		public int getStatus() {
			return status;
		}

		public void setStatus(int status) {
			this.status = status;
		}

		public Times() {

		}

		public String getId() {
			return id;
		}

		public void setId(String id) {
			this.id = id;
		}

	}
}
